package com.yxsk.relay.job.component.endpoint.net;

import com.alibaba.fastjson.JSONObject;
import com.yxsk.relay.job.component.common.net.handler.exception.GlobalNetServerExceptionHandler;
import com.yxsk.relay.job.component.common.net.message.NetResponseMessage;
import com.yxsk.relay.job.component.common.protocol.message.base.ResponseCodes;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description
 * @Author 11376
 * @CreateTime 2019/9/9 11:02
 */
@Slf4j
public class RestfulGlobalNetExceptionHandler implements GlobalNetServerExceptionHandler {

    @Override
    public NetResponseMessage handle(ExceptionEvent e) {
        if (log.isErrorEnabled()) {
            log.error("Restful net server caught", e.getCause());
        }

        // 响应
        ResultResponse response = ResultResponse.fail(ResponseCodes.INTERNAL_ERROR.getCode(), e.getCause().getMessage());
        String json = JSONObject.toJSONString(response);

        // 响应头
        Map<String, String> headers = new TreeMap<>();
        headers.put("Content-Type", "application/json");

        return NetResponseMessage.builder()
                .message(json.getBytes(StandardCharsets.UTF_8))
                .status(HttpResponseStatus.OK.getCode())
                .headers(headers)
                .build();
    }

}
